﻿using CsvHelper;
using Delphi.Janus.Util;
using Delphi.Mimir.Data.Bulk;
using Delphi.Mimir.Data.Entities.Final;
using Delphi.Mimir.Data.Entities.Raw;
using Delphi.Mimir.Data.Procedures;
using Delphi.Mimir.Wrapper;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;

namespace Delphi.Mimir.Migrations {
    public class EodFile {

        public void Import(string folderPath, string extension = ".txt") {
            Console.WriteLine("Importing EodFiles");
            

            foreach(string f in Directory.EnumerateFiles(folderPath, string.Format("*{0}", extension)).Select(Path.GetFileName)) {
                Console.Write(string.Format("Importing {0} ...", f));

                using (Stream stream = new FileStream(folderPath + @"\" + f, FileMode.Open, FileAccess.Read) ) {
                    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) {
                        CsvReader csvReader = new CsvReader(reader);
                        csvReader.Configuration.WillThrowOnMissingField = false;
                        int counter = 0;
                        string loadType = "";

                        // Get exchange code from filename
                        string[] fSplitted = f.Split('_');

                        IList<RawQuote> quotes = new List<RawQuote>();
                        Exchange exc = ExchangeWrapper.GetExchange(fSplitted[0]);
                        //Exchange exc = ExchangeWrapper.GetExchange("AMEX");
                        DateTime date = DateTime.ParseExact(fSplitted[1].GetFirst(8), "yyyyMMdd", CultureInfo.InvariantCulture);

                        while (csvReader.Read()) {
                            ++counter;
                            RawQuote q = new RawQuote();

                            if(!string.IsNullOrEmpty(exc.Suffix)) { 
                                q.qot_sym_cd = csvReader.GetField("<ticker>").Replace("." + exc.Suffix, "");
                            } else {
                                q.qot_sym_cd = csvReader.GetField("<ticker>");
                            }
                            
                            q.qot_exc_cd = fSplitted[0];

                            // convert trade date to DateTime and destinguish btwn daily and minute dates
                            string tradeDate = csvReader.GetField("<date>");
                            if (tradeDate.Length == 8) {
                                q.qot_trade_dt = DateTime.ParseExact(tradeDate, "yyyyMMdd", CultureInfo.InvariantCulture);
                                q.qot_period = "D";
                                loadType = "QOTEOD";
                            } else if (tradeDate.Length == 12) {
                                q.qot_trade_dt = DateTime.ParseExact(tradeDate, "yyyyMMddHHmm", CultureInfo.InvariantCulture);
                                q.qot_period = "1";
                                loadType = "QOTINTRA";
                            }

                            q.qot_open = csvReader.GetField<Decimal>("<open>");
                            q.qot_high = csvReader.GetField<Decimal>("<high>");
                            var test = csvReader.GetField<string>("<low>");
                            q.qot_low = csvReader.GetField<Decimal>("<low>");
                            q.qot_close = csvReader.GetField<Decimal>("<close>");
                            q.qot_volume = csvReader.GetField<long>("<vol>");
                            q.qot_open_interest = csvReader.GetField<int>("<oi>");

                            quotes.Add(q);
                        }
                        Etl.ClearTable("raw.eod_quotes");
                        BulkLoad bulk = BulkLoad.GetInstance();
                        bulk.Persist(quotes.ToArray());
                        Etl.EodQuotesApi();
                        Etl.ClearTable("raw.eod_quotes");
                        // public static void AddNewLoad(string exchangeCode, string loadType, DateTime tradeDate, int records, string status) {
                        LoadControlWrapper.AddNewLoad(exc.Code, loadType, date, counter, "Success");
                    }
                    Console.WriteLine(" Done");
                }
            }
        }
    }
}
